package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse<User> login(String username, String password) {
//        校验
        int resultCount = userMapper.checkUsername(username);
        if (resultCount ==0 ){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
//        todo 密码登录MD5
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(username,md5Password);
        if(user == null){
            return ServerResponse.createByErrorMessage("密码错误");
        }
//        处理返回值的密码   设置为空
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);

    }

    /**
     *
     * @param user
     * @return
     */
    public ServerResponse<String> register(User user) {

        ServerResponse validResponse = this.checkValid(user.getUsername(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(),Const.USERNAME);
        if(!validResponse.isSuccess()){
            return validResponse;
        }



//        默认设置成普通用户
        user.setRole(Const.Role.ROLE_CUSTOMER);
//        MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount ==0) {
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccess("注册成功！");

    }

    /**
     *
     * @param str
     * @param type
     * @return
     */
    public ServerResponse<String> checkValid(String str, String type){
    if(StringUtils.isNotBlank(type)){
//        开始校验
        if(Const.USERNAME.equals(type)){
            int resultCount = userMapper.checkUsername(str);
            if (resultCount > 0 ){
                return ServerResponse.createByErrorMessage("用户名已存在");
            }
        }
        if(Const.EMAIL.equals(type)){
            int resultCount = userMapper.checkEmail(str);
            if(resultCount>0){
                return  ServerResponse.createByErrorMessage("email已存在");
            }
        }

    }else {
        return ServerResponse.createByErrorMessage("参数错误");
    }
    return ServerResponse.createBySuccessMessage("校验成功");
    }

    /**
     *
     * @param username
     * @return
     */
    public ServerResponse selectQuestion(String username){
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);

        if(validResponse.isSuccess()){
//            用户不存在
            return    ServerResponse.createByError().createByErrorMessage("用户不存在！");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNoneBlank(question)){
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("密码为空！");
    }

    /**
     *
     * @param username
     * @param question
     * @param answer
     * @return
     */
//    public static void main(String[] args) {
//        System.out.println(UUID.randomUUID().toString());
//    }
    public ServerResponse<String> checkAnswer(String username,String question,String answer){
        int resultCount = userMapper.checkAnswer(username,question,answer);
        if(resultCount>0){
//            说明问题和回答是这个用户，并且是正确的
            String forgetToken = UUID.randomUUID().toString();
//将本地的token中放入本地cache,并设置有效期
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServerResponse.createBySuccess(forgetToken);
        }
        return ServerResponse.createByErrorMessage("问题的答案错误！");
    }

    /**
     * 这里要理解为什要有token，主要是防止横向越权，可能a用户用自己的帐号，重置了b的密码
     * @param username
     * @param passwordNew
     * @param forgetToken
     * @return
     */
    public ServerResponse forgetResetPassword(String username,String passwordNew,String forgetToken){
        if(StringUtils.isNoneBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误，token需要传递进来");
        }
        ServerResponse validResponse = this.checkValid(username, Const.USERNAME);

        if(validResponse.isSuccess()){
//            用户不存在
            return    ServerResponse.createByError().createByErrorMessage("用户不存在！");
        }
        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
        if(StringUtils.isNoneBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或过期");
        }
        if(StringUtils.equals(forgetToken,token)){
            String MD5Password = MD5Util.MD5EncodeUtf8(passwordNew);
//            更新密码需要使用MD5加密之后的密码
            int rowCount = userMapper.updatePasswordByUsername(username,MD5Password);

            if(rowCount>0){
                return ServerResponse.createBySuccessMessage("密码修改成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码的token");
        }
        return ServerResponse.createByErrorMessage("密码修改失败");

    }

    public ServerResponse<String> resetPassword(String passwordOLd, String passwordNew,User user){
//        防止横向越权，要校验这个用户的旧密码，一定要制定这个用户，因为我们会查询一个count（1），如果不指定id，那么结果就是true;count>0
        int reslutCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOLd),user.getId());
        if(reslutCount==0){
            return  ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
//        选择性的更新，哪个不为空就更新那个
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }
//// TODO: 17-11-15
    public ServerResponse<User> updateInformation(User user){
        //username不能被更新
        //email 需要验证，校验新的email已经存在，并且存在email相同的话，不能是我们当前这个用户
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(),user.getId());

        if(resultCount>0){
        return ServerResponse.createByErrorMessage("email已经存在，请更换email");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setAnswer(user.getAnswer());
        updateUser.setQuestion(user.getQuestion());

        int updateCount  = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount>0){
            return ServerResponse.createBySuccessMessage("用户信息更新成功");
        }
        return ServerResponse.createByErrorMessage("用户信息更新失败");
    }
//        ServerResponse validEmail = checkValid(user.getEmail(),Const.EMAIL);
//        if(validEmail.isSuccess()){
//            return ServerResponse.createByErrorMessage("当前email已经被注册");
//        }
//        ServerResponse validsername= checkValid(user.getUsername(),Const.USERNAME);
//        if(validsername.isSuccess()){
//            return ServerResponse.createByErrorMessage("用户名无法修改");
//        }
//        return ServerResponse.createBySuccessMessage("修改成功");
//    }

    public ServerResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if (user ==null){
            return ServerResponse.createByErrorMessage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(user);
    }
}
